package com.waikuai.shop.service.impl;

import com.waikuai.shop.entity.User;
import com.waikuai.shop.mapper.UserMapper;
import com.waikuai.shop.service.*;
import com.waikuai.shop.vo.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 首页服务实现类
 * @author waikuai
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class HomeServiceImpl implements HomeService {

    private final UserService userService;
    private final ProductService productService;
    private final ProductCategoryService productCategoryService;
    private final WelfareCardService welfareCardService;
    private final ShoppingCartService shoppingCartService;
    private final UserFavoriteService userFavoriteService;
    private final UserMapper userMapper;

    @Override
    public HomePageVO getHomePageData(Long userId) {
        try {
            HomePageVO homePageVO = new HomePageVO();

            // 获取用户信息
            User user = userMapper.selectById(userId);
            if (user != null) {
                homePageVO.setAccountBalance(user.getAccountBalance() != null ?
                    BigDecimal.valueOf(user.getAccountBalance()) : BigDecimal.ZERO);
            }

            // 获取额度卡信息
            BigDecimal availableCardAmount = welfareCardService.sumAvailableAmountByUserId(userId);
            homePageVO.setAvailableCardAmount(availableCardAmount);
            homePageVO.setAvailableCardCount(welfareCardService.getUserCards(userId, 1).size());

            // 获取购物车和收藏数量
            homePageVO.setCartItemCount(shoppingCartService.countCartItems(userId));
            homePageVO.setFavoriteCount(userFavoriteService.countUserFavorites(userId));

            // 待处理订单数量（暂时设为0，后续实现订单服务时再完善）
            homePageVO.setPendingOrderCount(0);

            // 获取热门商品
            List<ProductSimpleVO> hotProducts = productService.getHotProducts(10);
            homePageVO.setHotProducts(hotProducts);

            // 获取推荐商品
            List<ProductSimpleVO> featuredProducts = productService.getFeaturedProducts(10);
            homePageVO.setFeaturedProducts(featuredProducts);

            // 获取商品分类
            List<CategoryTreeVO> categories = productCategoryService.getCategoryTree();
            homePageVO.setCategories(categories);

            // 最新通知（暂时设为空，后续实现通知服务时再完善）
            homePageVO.setNotifications(Collections.emptyList());

            // 系统公告
            homePageVO.setSystemAnnouncement("欢迎使用员工关怀在线商城！这里有最新的福利信息和热门商品推荐。");

            log.info("获取首页数据成功，用户ID: {}", userId);
            return homePageVO;
        } catch (Exception e) {
            log.error("获取首页数据失败，用户ID: {}, 错误: {}", userId, e.getMessage(), e);
            throw new RuntimeException("获取首页数据失败");
        }
    }

    @Override
    public HomePageVO getHomePageDataForGuest() {
        try {
            HomePageVO homePageVO = new HomePageVO();

            // 游客模式，设置默认值
            homePageVO.setAccountBalance(BigDecimal.ZERO);
            homePageVO.setAvailableCardAmount(BigDecimal.ZERO);
            homePageVO.setAvailableCardCount(0);
            homePageVO.setCartItemCount(0);
            homePageVO.setFavoriteCount(0);
            homePageVO.setPendingOrderCount(0);

            // 获取热门商品
            List<ProductSimpleVO> hotProducts = productService.getHotProducts(10);
            homePageVO.setHotProducts(hotProducts);

            // 获取推荐商品
            List<ProductSimpleVO> featuredProducts = productService.getFeaturedProducts(10);
            homePageVO.setFeaturedProducts(featuredProducts);

            // 获取商品分类
            List<CategoryTreeVO> categories = productCategoryService.getCategoryTree();
            homePageVO.setCategories(categories);

            // 最新通知
            homePageVO.setNotifications(Collections.emptyList());

            // 系统公告
            homePageVO.setSystemAnnouncement("欢迎使用员工关怀在线商城！请先登录以享受完整服务。");

            log.info("获取游客首页数据成功");
            return homePageVO;
        } catch (Exception e) {
            log.error("获取游客首页数据失败: {}", e.getMessage(), e);
            throw new RuntimeException("获取首页数据失败");
        }
    }

    @Override
    public void refreshHomePageCache(Long userId) {
        try {
            // 这里可以实现缓存刷新逻辑
            // 暂时只是记录日志
            log.info("刷新首页缓存，用户ID: {}", userId);

            // 实际项目中可能需要：
            // 1. 清除Redis中的用户首页缓存
            // 2. 重新加载用户信息
            // 3. 重新计算统计数据
            // 4. 更新缓存

        } catch (Exception e) {
            log.error("刷新首页缓存失败，用户ID: {}, 错误: {}", userId, e.getMessage(), e);
            throw new RuntimeException("刷新首页缓存失败");
        }
    }
}
